"use client"

import { useState } from "react"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { apiCall } from "@/lib/mock-api"
import { toast } from "@/hooks/use-toast"

interface CreateFolderDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  onCreateSuccess?: () => void
  parentId?: number // 当前目录的 ID，默认为 0（根目录）
}

export function CreateFolderDialog({ open, onOpenChange, onCreateSuccess, parentId = 0 }: CreateFolderDialogProps) {
  const [folderName, setFolderName] = useState("")
  const [isLoading, setIsLoading] = useState(false)

  const handleCreate = async () => {
    if (!folderName.trim()) return

    setIsLoading(true)
    try {
      await apiCall(
        "/api/files/folder",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ parentId, folderName }),
        },
        {
          success: true,
          folderId: Math.floor(Math.random() * 1000000),
          folderName,
        },
      )

      toast({
        title: "创建成功",
        description: `文件夹 "${folderName}" 已创建`,
        variant: "success",
        duration: 3000,
      })

      setFolderName("")
      onOpenChange(false)
      onCreateSuccess?.()
    } catch (error) {
      console.error("Failed to create folder:", error)
      toast({
        title: "创建失败",
        description: "文件夹创建过程中出现错误",
        variant: "destructive",
        duration: 3000,
      })
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>新建文件夹</DialogTitle>
          <DialogDescription>创建一个新的文件夹来组织您的文件</DialogDescription>
        </DialogHeader>

        <div className="space-y-4 py-4">
          <div className="space-y-2">
            <Label htmlFor="folder-name">文件夹名称</Label>
            <Input
              id="folder-name"
              placeholder="请输入文件夹名称"
              value={folderName}
              onChange={(e) => setFolderName(e.target.value)}
              onKeyDown={(e) => e.key === "Enter" && handleCreate()}
            />
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={isLoading}>
            取消
          </Button>
          <Button onClick={handleCreate} disabled={!folderName.trim() || isLoading}>
            {isLoading ? "创建中..." : "创建"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
